<template>
  <van-form>
    <van-cell-group inset>
      <van-field
        v-model="metric"
        type="number"
        :label="metricLabel"
        @blur="metricToImperial"
        right-icon="more-o"
        @click-right-icon="togglePicker('metric')"
      />
      <van-field
        v-model="imperial"
        type="number"
        :label="imperialLabel"
        @blur="imperialToMetric"
        right-icon="more-o"
        @click-right-icon="togglePicker('imperial')"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary"> 转换 </van-button>
    </div>
  </van-form>

  <van-popup v-model:show="showPicker" round position="bottom">
    <van-picker
      :columns="columns"
      @cancel="showPicker = false"
      @confirm="onConfirm"
    />
  </van-popup>
</template>

<script setup>
import { ref } from 'vue';

const showPicker = ref(false);

const onConfirm = ({ selectedOptions }) => {
  showPicker.value = false;

  const fieldText = selectedOptions[0].text;
  const fieldValue = selectedOptions[0].value;

  if (columns.length === 2) {
    imperialUnit.value = Number(fieldValue);
    imperialLabel.value = fieldText;

    imperialToMetric();

    return;
  }

  metricUnit.value = Number(fieldValue);
  metricLabel.value = fieldText;

  metricToImperial();
};

const metricList = [
  { text: 'cm', value: '1' },
  { text: 'mm', value: '0.1' },
  { text: 'm', value: '100' },
];
const imperialList = [
  { text: 'in', value: '1' },
  { text: 'ft', value: '12' },
];

let columns = [];

const metric = ref(0);
const metricUnit = ref(1);
const metricLabel = ref('cm');

const imperial = ref(0);
const imperialUnit = ref(1);
const imperialLabel = ref('in');

function metricToImperial() {
  // metric to centimeter than to inch
  const inchNum = Number(((metric.value * metricUnit.value) / 2.54).toFixed(2));
  imperial.value = Number((inchNum / imperialUnit.value).toFixed(2));
}

function imperialToMetric() {
  // imperial to inch than to centimeter
  const centimeterNum = Number(
    imperial.value * imperialUnit.value * 2.54
  ).toFixed(2);
  metric.value = Number((centimeterNum / metricUnit.value).toFixed(2));
}

function togglePicker(unit) {
  showPicker.value = true;

  if (unit === 'metric') {
    columns = metricList;
    return;
  }

  columns = imperialList;
}
</script>
